# coding=utf-8
__author__ = 'Vlad'

from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.keys import Keys
import sys, time, random

sys.path.append('C:\\')
driver = webdriver.Firefox()
workspace_dir = 'D:\\'
driver.implicitly_wait(5)

#Функция для клика по кнопке при известном XPATH
#0 - XPATH-путь к кнопке
#1 - Сообщение, которое выводится в консоль при не обнаружение данной кнопки
#2 - Часть имени скриншота, который снимается при этом
def btn_xpath_click(btn_xpath, message1='', message2=''):
    try:
        driver.find_element_by_xpath(btn_xpath).click()
        time.sleep(0.1)
    except NoSuchElementException, e:
        print message1
        driver.get_screenshot_as_file(workspace_dir + str(time.strftime("%Y%m%d-%H%M%S", time.localtime())) + '-' + message2 + '.png')
        driver.quit()
        print driver.title

#Open url
test_url = 'http://localhost/php4dvd/'
driver.get(test_url)

#Authorization
driver.find_element_by_id("username").clear()
driver.find_element_by_id("username").send_keys("admin")
driver.find_element_by_name("password").clear()
driver.find_element_by_name("password").send_keys("admin")
driver.find_element_by_name("submit").click()
if 'Log out' not in driver.find_element_by_xpath("//*[@id='wrapper']/header/div/nav/ul/li[4]/a").text:
    print 'We have some problem with authorization'
    driver.quit()
    print driver.title
else:
    print 'Successfully logged in'

#checking general quatity of dvds already on the page
quantity=len(driver.find_elements_by_xpath("//*[@id='results']/a"))

if not quantity:
    print 'You have no items, so search cannot be checked correctly. Please add at least one'
    driver.quit()
    print driver.title

search=driver.find_element_by_xpath("//*[@class='title']").text

driver.find_element_by_id("q").clear()
driver.find_element_by_id("q").click()
driver.find_element_by_id("q").send_keys(search)
driver.find_element_by_id("q").send_keys(Keys.RETURN)

if driver.find_element_by_xpath("//*[@class='title']").text != search:
    print 'We have problem with the search'
    driver.quit()
    print driver.title
else:
    print 'Search is fine'

time.sleep(5)

driver.find_element_by_id("q").clear()
driver.find_element_by_id("q").click()
driver.find_element_by_id("q").send_keys('QzdnZPpkVGyZ6v3mgp')
driver.find_element_by_id("q").send_keys(Keys.RETURN)

if driver.find_element_by_xpath("//*[@class='content']").text != 'No movies where found.':
    print 'We have problem with the search'
    driver.quit()
    print driver.title
else:
    print 'Search is fine'

time.sleep(5)

driver.quit()